/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fujitsu.nanjing.tieba.base.BaseController;
import com.fujitsu.nanjing.tieba.common.ThirdVelocityEmailService;
import com.fujitsu.nanjing.tieba.exception.Resource404Exception;
import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.service.UserService;
import com.fujitsu.nanjing.tieba.view.velocity.tools.DomainTool;
import com.fujitsu.nanjing.tieba.view.velocity.tools.EncryptTool;

/**
 * ForumController.java
 * 
 * @author Qixiaobo-win8
 */
@Controller
@RequestMapping("/myforum")
public class ForumController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private ThirdVelocityEmailService thirdVelocityEmailService;
	@Autowired
	@Qualifier("org.springframework.security.authenticationManager")
	protected AuthenticationManager authenticationManager;
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(Model model) {
		return "/myforum/register";

	}
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String doRegister(Model model, CoreUser user, HttpSession session,
			String verifycode, HttpServletRequest request) {
		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (code.equals(verifycode)) {
			user.setRemoteip(request.getRemoteAddr());
			user.setCreatetime(new Date());
			user.setPwd(encrypt(user.getPwd()));
			if (user.getNickname() == null
					|| user.getNickname().trim().equals("")) {
				user.setNickname(user.getUserid());
			}
			user = userService.insert(user);
			model.addAttribute("user", user);
			setLoginState(session, userService.getUserName(user.getUserid()),
					user.getUserid(), user.getLastvisited());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user", user);
			authenticateUserAndSetSession(user, request);
			thirdVelocityEmailService.sendEmail(map,
					"欢迎来到" + new DomainTool().getDomain(),
					"com/fujitsu/mailTemplates/welcome.vm",
					new String[]{user.getEmail()}, new String[]{});
			return redirect("/perform/" + encrypt(user.getUserid()));

		}
		return "/myforum/register";

	}
	@RequestMapping(value = "/perform/{userid}", method = RequestMethod.GET)
	public String perform(Model model, @PathVariable String userid,
			HttpServletRequest request) throws Resource404Exception {
		userid = decrypt(userid);
		if (userid == null || !userid.equals(getUserDetails().getUsername())) {
			throw new Resource404Exception("请只访问本人的页面！");
		}
		CoreUser user = userService.findById(userid);
		user.setPwd(decrypt(user.getPwd()));
		model.addAttribute("user", user);
		// TODO;存放着上次访问的页面
		// model.addAttribute("lastAccessUrl", getLastAccessUrl(request));
		return "myforum/peform";
	}
	/**
	 * ajax校验用户名是否被占用
	 * */
	@RequestMapping(value = "/checkUserId", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkUserId(Model model, String userid) {
		CoreUser user = userService.findById(userid);
		if (user != null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * ajax校验邮箱是否被占用
	 * */
	@RequestMapping(value = "/checkEmail", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkEmail(Model model, String email) {
		int count = userService.findByEmail(email);
		if (count != 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * ajax校验验证码是否正确
	 * */
	@RequestMapping(value = "/checkVerifyCode", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkVerifyCode(Model model, String verifycode,
			HttpSession session) {
		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (!code.equals(verifycode)) {
			return false;
		} else {
			return true;
		}
	}
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, Model model) {
		// model.addAttribute("lastAccessUrl", getLastAccessUrl(request));
		return "/myforum/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String doLogin(Model model, String j_username, String j_password,
			String _spring_security_remember_me, String fromPath,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		String cookietime = "0";
		if (_spring_security_remember_me != null) {
			cookietime = Integer.toString(2 * 7 * 24 * 60 * 60);
		}
		CoreUser user = userService.findById(j_username);
		if (user == null) {
			model.addAttribute("error", "true");
			return redirect("/login");
		}
		if (!userService.checkUserState(j_username)) {
			model.addAttribute("error", "lock");
			return redirect("/login");
		}
		if (!user.getPwd().equals(encrypt(j_password))) {
			model.addAttribute("error", "true");
			userService.updateUserStateWhileError(user);
			return redirect("/login");
		}
		setLoginState(session, userService.getUserName(user.getUserid()),
				user.getUserid(), user.getLastvisited());
		setCookie(cookietime, j_username, request, response);
		userService.updateWhileLogin(user, cookietime);
		userService.updateUserStateWhileNomal(user);
		// 更新时间
		if (fromPath != null && !fromPath.trim().equals("")) {
			return redirect(fromPath);
		}
		return redirect("/");
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logOut(Model model, HttpSession session) {
		setLogOutStatus(session);
		return redirect("/");
	}
	// 设置Cookie
	public void setCookie(String cookietime, String userid,
			HttpServletRequest request, HttpServletResponse response) {
		if (!cookietime.equals("0")) {
			setCookie(request, response, CURRENTUSER,
					userService.getUserName(userid),
					Integer.parseInt(cookietime));
			setCookie(request, response, USERID, userid,
					Integer.parseInt(cookietime));
		}
	}
	private void authenticateUserAndSetSession(CoreUser user,
			HttpServletRequest request) {
		try {
			UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
					user.getUserid(), new EncryptTool().decrypt(user.getPwd()));

			// generate session if one doesn't exist
			request.getSession();

			token.setDetails(new WebAuthenticationDetails(request));

			Authentication authenticatedUser = authenticationManager
					.authenticate(token);

			SecurityContextHolder.getContext().setAuthentication(
					authenticatedUser);
		} catch (BadCredentialsException e) {
			logger.error("BadCredentialsException: " + e.getLocalizedMessage());
		}
	}
}
